<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          统计月份:
          <NDatePicker input-readonly style="width: 300rem" placeholder="请选择统计时间" type="daterange" clearable
            v-model:formatted-value="range" />
          选择部门:
          <NSelect style="width: 200rem" placeholder="请选择部门" v-model:value="paginationReactive.deptId" clearable
            :options="bbgDeptList" label-field="name" value-field="value" filterable />
          公务接待事由:
          <NInput v-model:value="paginationReactive.receptionContent" placeholder="请输入公务接待事由" clearable
            class="commonWidth" />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getAllOverTimeList())">
            查询
          </NButton>
        </NSpace>
        <NButton type="primary" style="width: 115rem" @click="deptExport" :loading="exportLoading" ghost>
          导出
        </NButton>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<script setup lang="ts">
import {
  NSpace, NButton, NDataTable, NPagination, useMessage, NSelect,
  NDatePicker, NInput
} from 'naive-ui'
import { h, reactive, ref, onMounted, onDeactivated, watch } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { OverTimeModel } from '@/api/overTime'
import type { HttpResponse } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'
import dayjs from 'dayjs'
const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()

const columns: any = [
  {
    title: '申请人',
    key: 'userName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '申请人部门',
    key: 'deptName',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '公务接待对象',
    key: 'receiver',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '接待人数',
    key: 'receptionNum',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '用餐种类',
    key: 'diningType',
    width: 80,
    align: useStore.isCenter,
    render: ({ diningType }: any) => {
      if (!diningType) return ''
      const tmp = diningType.split(',')
      const result = tmp.map((it: any) => parentCodeList.value.find((c: any) => it == c.dicCode)?.dicName)
      return result.map((it: any) => it).join('，')
    }
  },
  {
    title: '公务接待事由',
    key: 'receptionContent',
    width: 120,
    align: useStore.isCenter
  },
  {
    title: '公务接待场所',
    key: 'addressType',
    width: 120,
    align: useStore.isCenter,
    render: ({ addressType }: any) => {
      return addressType == '0' ? '馆内' : addressType == '1' ? '馆外' : ''
    }
  },
  {
    title: '公务接待日期',
    key: 'receptionTime',
    width: 80,
    align: useStore.isCenter,
    render: ({ receptionTime }: any) => {
      return receptionTime.split(' ')[0]
    }
  },
  {
    title: '申请日期',
    key: 'createTime',
    width: 80,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 80,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0502')
            router.push({ path: '/OA/HaveDinner/HaveDinnerInfo', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      row.fromStatusCode === 'A0605' && h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          loading: row.exportLoading || false,
          onClick: () => {
            exportSingle(String(row.id))
          }
        },
        {
          default: () => '导出'
        }
      ),
    ]
  }
]
//类型
const parentCodeList: any = ref([])
const getParentCode = async () => {
  const [error, res] = await sendRequest({
    module: 'progress',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A60'
      }
    }
  })
  if (error) return
  if (res.code != 0) return
  parentCodeList.value = res.data
}
const exportSingle = async (id: string) => {
  tableData.value.forEach((t: any) => {
    t.exportLoading = (String(t.id) === id)
  })
  const [error, data, headers] = await sendRequest<HttpResponse>({
    module: 'haveDinner',
    api: 'diningExport',
    override: {
      params: {
        id
      }
    }
  })
  if (error) {
    tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
    message.error("导出出错")
    throw new Error("导出出错")
  }
  tableData.value.forEach((t: any) => {
    t.exportLoading = false
  })
  download(headers, data, '公务接待审批单')
  message.success("导出成功")
}
const exportLoading = ref<boolean>(false);
const deptExport = async () => {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'haveDinner',
    api: 'diningListExport',
    override: {
      params: {
        page: paginationReactive.page,
        limit: 99999,
        receptionContent: paginationReactive.receptionContent,
        deptId: paginationReactive.deptId,
        startTime: range.value[0] ? dayjs(range.value[0]).format('YYYY-MM-DD') : null,
        endTime: range.value[1] ? dayjs(range.value[1]).format('YYYY-MM-DD') : null
      }
    }
  })
  if (error) return message.error(error.message), (exportLoading.value = false)
  download(headers, res, '部门接待统计')
  message.success('导出成功')
  exportLoading.value = false
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
// 上一页下一页
const paginationReactive = reactive<Record<string, any>>({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  receptionContent: null, //接待事由
  deptId: null, //部门
  startTime: null, //开始时间
  endTime: null, //结束时间
  onChange: (page: number) => {
    paginationReactive.page = page
    getAllOverTimeList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getAllOverTimeList()
  }
})
// 开始时间选择
const range = ref()
const handleFormattedStart = (v: any) => {
  range.value = v
  if (v) (paginationReactive.startStartTime = v[0]), (paginationReactive.startEndTime = v[1])
  else (paginationReactive.startStartTime = null), (paginationReactive.startEndTime = null)
}
//部门
const bbgDeptList: any = ref([])
const getBbgDeptList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  bbgDeptList.value = res.data
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getAllOverTimeList = async () => {
  tableLoading.value = true
  console.log(paginationReactive.startTime)
  console.log(paginationReactive.endTime)
  const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
    module: 'haveDinner',
    api: 'diningAllList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        receptionContent: paginationReactive.receptionContent,
        deptId: paginationReactive.deptId,
        startTime: range.value[0] ? dayjs(range.value[0]).format('YYYY-MM-DD') : null,
        endTime: range.value[1] ? dayjs(range.value[1]).format('YYYY-MM-DD') : null
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list.map((t: any) => {
    return {
      ...t,
      exportLoading: false
    }
  })
  paginationReactive.itemCount = res.data.totalCount
}
//当前月第一天
function getFirstDay() {
  let y: any = new Date().getFullYear() //获取年份
  let m: any = new Date().getMonth() + 1 //获取月份
  let d: any = '01'
  m = m < 10 ? '0' + m : m //月份补 0
  return [y, m, d].join('-')
}
//当前月最后一天
function getLastDay() {
  let y: any = new Date().getFullYear() //获取年份
  let m: any = new Date().getMonth() + 1 //获取月份
  let d: any = new Date(y, m, 0).getDate() //获取当月最后一日
  m = m < 10 ? '0' + m : m //月份补 0
  d = d < 10 ? '0' + d : d //日数补 0
  return [y, m, d].join('-')
}

onMounted(async () => {
  range.value = [getFirstDay(), getLastDay()]
  paginationReactive.startTime = range.value[0]
  paginationReactive.endTime = range.value[1]
  await getParentCode()
  getBbgDeptList()
  getAllOverTimeList()
})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1, getAllOverTimeList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/HaveDinner/allHaveDinner') {
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
